#!/usr/bin/env bash


_W_DEVICE=${_W_DEVICE:-en0}

help(){
    cat<<__EOF__
    usage:  m wifi [ scan | off | on | connect | help ]

    Examples:
      m wifi status                  # wifi status
      m wifi scan                    # scan wifi
      m wifi showpassword [ESSID]    # show wifi network password (default: current)
      m wifi history                 # wifi connection history
      m wifi off                     # turn off your wifi
      m wifi on                      # turn on your wifi
      m wifi connect ESSID PASSWORD  # join a wifi network
__EOF__
}

wifi_status(){
    /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I
}

wifi_scan(){
    /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s
}

wifi_history(){
    defaults read /Library/Preferences/SystemConfiguration/com.apple.airport.preferences | grep LastConnected -A 7
}

wifi_showpassword(){
    if [ -z "$1" ]
    then
        ssid="`/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk '/ SSID/ {print substr($0, index($0, $2))}'`"
    else
        ssid=$1
    fi
    security find-generic-password -D "AirPort network password" -a "$ssid" -gw
}

wifi_off(){
    networksetup -setairportpower ${_W_DEVICE} off
}

wifi_on(){
    networksetup -setairportpower ${_W_DEVICE} on
}

connect_network(){
    [ -z "$1" -o -z "$2" ] && help
    NETWORK="$1"
    shift
    networksetup -setairportnetwork "${_W_DEVICE}" "${NETWORK}" "$@"
}

case $1 in
    help)
        help
        ;;
    scan)
        wifi_scan
        ;;
    status)
        wifi_status
        ;;
    off)
        wifi_off
        ;;
    on)
        wifi_on
        ;;
    connect)
        shift
        connect_network "$@"
        ;;
    history)
        shift
        wifi_history
        ;;
    showpassword)
        shift
        wifi_showpassword "$@"
        ;;
    *)
        help
        ;;
esac

# vim: ts=4 sw=4 softtabstop=4 expandtab
